import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import type { ApiResponse } from '@/types'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: 'https://www.lostpethk.com/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  },
)

// API请求封装函数
export const apiRequest = {
  // GET请求
  get: async <T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
    try {
      const response = await api.get(url, config)
      return response.data
    } catch (error: any) {
      throw error.response?.data || { success: false, message: '请求失败' }
    }
  },

  // POST请求
  post: async <T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<ApiResponse<T>> => {
    try {
      const response = await api.post(url, data, config)
      return response.data
    } catch (error: any) {
      throw error.response?.data || { success: false, message: '请求失败' }
    }
  },

  // PUT请求
  put: async <T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<ApiResponse<T>> => {
    try {
      const response = await api.put(url, data, config)
      return response.data
    } catch (error: any) {
      throw error.response?.data || { success: false, message: '请求失败' }
    }
  },

  // PATCH请求
  patch: async <T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<ApiResponse<T>> => {
    try {
      const response = await api.patch(url, data, config)
      return response.data
    } catch (error: any) {
      throw error.response?.data || { success: false, message: '请求失败' }
    }
  },

  // DELETE请求
  delete: async <T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> => {
    try {
      const response = await api.delete(url, config)
      return response.data
    } catch (error: any) {
      throw error.response?.data || { success: false, message: '请求失败' }
    }
  },

  // 文件上传请求
  upload: async <T = any>(
    url: string,
    formData: FormData,
    config?: AxiosRequestConfig & { method?: 'POST' | 'PUT' | 'PATCH' },
  ): Promise<ApiResponse<T>> => {
    try {
      const method = config?.method || 'POST'
      const { method: _, ...restConfig } = config || {}

      const response = await api.request({
        method,
        url,
        data: formData,
        ...restConfig,
        headers: {
          'Content-Type': 'multipart/form-data',
          ...restConfig?.headers,
        },
      })
      return response.data
    } catch (error: any) {
      throw error.response?.data || { success: false, message: '上传失败' }
    }
  },
}

export default api
